#coding:utf-8
from PySide import QtWebKit
from PySide import QtCore, QtGui
from ebook4us_ui import Ui_MainWindow
from greader import GReader
import sys

 
class Worker(QtCore.QThread):
    done = QtCore.Signal(object)
    func = None
    
    def __init__(self,parent=None):
        QtCore.QThread.__init__(self, parent)
        self.mutex = QtCore.QMutex()
        
    def call(self,func,cbk,args=None):
        self.mutex.tryLock(200)
        self.done.disconnect()  
        self.done.connect(cbk,QtCore.Qt.QueuedConnection)  
        self.func = func
        self.args = args
        self.mutex.unlock()
    
    def run(self):
        while True:
            self.mutex.lock()
            if self.func:
                try:
                    self.result = self.func(self.args)
                    self.done.emit(self.result)
                except Exception, e:
                    print e
                    self.done.emit(None)
                finally:
                    self.func = None
                    self.args = {}
                    self.mutex.unlock()
            self.msleep(500)

 
    

class MainApp:
    def __init__(self):
        self.gclient = GReader()
        self.config = QtCore.QSettings('./settings.conf',QtCore.QSettings.IniFormat)
        
        self.app = QtGui.QApplication(sys.argv)
        self.MainWindow = QtGui.QMainWindow()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self.MainWindow)
        
        self.createActions()
        self.createMenus()
        self.initApp()
        
        self.work = Worker()
        self.work.start()
        
        self.MainWindow.show()
        sys.exit(self.app.exec_())
        
    def createActions(self):
        self.exitAct = QtGui.QAction("E&xit", self.MainWindow, shortcut="Ctrl+Q",
                statusTip="Exit the application", triggered=self.close)
        
        self.aboutAct = QtGui.QAction("&About", self.MainWindow,
                statusTip="Show the application's About box",triggered=self.about)
        
    def createMenus(self):
        self.fileMenu = self.MainWindow.menuBar().addMenu("&File")
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.exitAct)
        self.helpMenu = self.MainWindow.menuBar().addMenu("&Help")
        self.helpMenu.addAction(self.aboutAct)
        
    def initApp(self):
        self.ui.account.setText(self.config.value("account",'yourname@gmail.com'))
        self.ui.passwd.setText(self.config.value("passwd",'passwd'))
        
        self.websettings = QtWebKit.QWebSettings.globalSettings()
        self.websettings.setUserStyleSheetUrl(QtCore.QUrl.fromLocalFile("./res/style.css"));
        
        self.ui.reloadCmd.clicked.connect(self.loadSubs)
        self.ui.loginCmd.clicked.connect(self.doLogin)
        self.ui.logoutCmd.clicked.connect(self.doLogout)
        self.ui.subslist.itemClicked.connect(self.loadRss)
        self.ui.feedlist.itemClicked.connect(self.viewFeed)
         
    def doLogin(self):  
        account,passwd = self.ui.account.text(),self.ui.passwd.text()
        @QtCore.Slot(object)
        def logincbk(data):
            print self.gclient.auth
            if self.gclient.auth is not None and  self.gclient.sid is not None:
                self.ui.loginCmd.setEnabled(True)
                self.ui.statusbar.showMessage(u"登录成功",5000)
                #check settings
                self.config.setValue('account',account)
                self.config.setValue('passwd',passwd)
                self.config.sync()
            else:
                self.ui.statusbar.showMessage(u"登录失败",5000)  
        
        if account and passwd:
            self.ui.loginCmd.setEnabled(False)
            self.ui.logoutCmd.setEnabled(True)
            self.ui.statusbar.showMessage(u"登录中...",60*1000)
            func = lambda args:self.gclient.doAuth(args['a'],args['p'])
            self.work.call(func,logincbk,{'a':account,'p':passwd})
        else:
            self.ui.statusbar.showMessage(u"帐号信息不完整",5000)
                
    def doLogout(self):
        self.ui.loginCmd.setEnabled(True)
        self.ui.logoutCmd.setEnabled(True)

    def loadSubs(self):
        #if self.gclient.auth is None:
        #    self.ui.statusbar.showMessage(u"还未登录",60*1000)   
        taglist, rss = [],{}
        self.ui.subslist.clear()
        def tagscbk(tags):
            def subscbk(subs):
                if subs:
                    subslist = subs['subscriptions'] 
                    for sub in subslist:
                        for tag in taglist:
                            if sub['categories'] and sub['categories'][0]['id'] == tag['id']:
                                if rss.get(tag['id']) is None:rss[tag['id']] = []
                                rss[tag['id']].append(sub)

                    print rss
                    for k,v in rss.items():
                        treeit = QtGui.QTreeWidgetItem()
                        treeit.setText(0,k[k.rindex('/')+1:])
                        icon = QtGui.QIcon("res/119.png")
                        treeit.setIcon(0, icon)
                        treeit.feedid = k
                        self.ui.subslist.addTopLevelItem(treeit)
                        
                        for subit in v:
                            subtreeit = QtGui.QTreeWidgetItem()
                            subtreeit.setText(0,subit['title'])
                            icon = QtGui.QIcon("res/1.png")
                            subtreeit.setIcon(0, icon)
                            subtreeit.feedid = subit['id']
                            treeit.addChild(subtreeit)
                        
                self.ui.statusbar.showMessage(u"加载完成",60*1000)               
            
            if tags:
                taglist = tags['tags']
                func = lambda args: self.gclient.loadSubs()      
                self.ui.statusbar.showMessage(u"加载列表中...",60*1000)     
                self.work.call(func,subscbk)
        
        tagfunc = lambda args: self.gclient.loadTags()      
        self.ui.statusbar.showMessage(u"加载目录中...",60*1000)     
        self.work.call(tagfunc,tagscbk)
        
    def loadRss(self,chkitem,col):
        self.ui.feedlist.clear()
        feedid = chkitem.feedid
        def cbk(rssdata):
            if rssdata:
                items = rssdata['items']
                for item in items:
                    icon = QtGui.QIcon("res/3.png")
                    litem = QtGui.QListWidgetItem()
                    litem.setIcon(icon)
                    litem.setText(item['title'])
                    litem.itemData = item
                    self.ui.feedlist.addItem(litem)
            
        rssfunc = lambda args: self.gclient.loadRss(args['id'])      
        self.ui.statusbar.showMessage(u"加载Rss中...",60*1000)     
        self.work.call(rssfunc,cbk,{'id':feedid})   
        
    def viewFeed(self,chkitem):
        item = chkitem.itemData
        content = ''
        if item.has_key('summary'):
            content = item['summary']['content']
        elif item.has_key('content'):
            content = item['content']['content']
        self.ui.webView.setHtml(content)
        
    def close(self):
        self.app.exit()
    
    def about(self):
        QtGui.QMessageBox.about(self.MainWindow, "About Menu","ebook4us by jamiesun!")

if __name__ == "__main__":
    mainapp = MainApp()

